package ThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/****
 *newCachedThreadPool创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。
 *newFixedThreadPool 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。
 * newScheduledThreadPool 创建一个定长线程池，支持定时及周期性任务执行。
 * newSingleThreadExecutor 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
 *
 * By Libofei
 * **/
public class ThreadPoolExecutor {

    public static void main(String[] args) {
//        newCachedThreadPool();
//        newFixedThreadPool();
//        newScheduledThreadPool();
//        newSingleThreadExecutor();
    }

    public static void newCachedThreadPool(){
        //1.可缓存线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0 ; i < 10 ;i++){
            final int item  = 1;
            executorService.execute(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ", i=" + item);
                }
            });
        }
//        executorService.shutdown();
    }

    public static  void newFixedThreadPool(){
        //2固定长度的线程池
        ExecutorService executorService  = Executors.newFixedThreadPool(3);
        for(int i =0 ; i < 10 ;i++){
            final int item = i;
            executorService.execute(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ",i=" + item);
                }
            });
        }
        executorService.shutdown();
    }

    public static void newScheduledThreadPool(){
        //3指定时间执行线程
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
        for(int i = 0 ; i<10 ; i++){
            final int item = i;
            scheduledExecutorService.schedule(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ",i=" + item);
                }
            },3, TimeUnit.SECONDS);
        }


    }

    public static void newSingleThreadExecutor(){
        //4单线程线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for(int i= 0 ; i < 10 ;i++){
            final int item = i ;
            executorService.execute(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(1000);
                    }catch (Exception e){

                    }

                    System.out.println(Thread.currentThread().getName() + ",i=" + item);
                }
            });
        }
        executorService.shutdown();  //会在线程执行结束后 关闭线程池
    }


    public static void executorFactory(){

    }
}
